<template>
  <el-form ref="ruleForm"
           :model="form"
           label-width="130px"
           class="create_form"
           label-position="right">
    <el-row :gutter="50">
      <el-col :offset="2"
              :span="8">
        <template v-for="(item, index) in shipData">
          <div v-if="item.fromContact && item.fromContact.length > 0"
               :key="index">
            <el-form-item v-for="(ele, i) in item.fromContact"
                          :key="i"
                          :label="ele.label"
                          :prop="`fromContact.${[ele.prop]}`"
                          :rules="[
                {
                  required: true,
                  message: `请输入${ele.label}`,
                  trigger: 'blur'
                }
              ]">
              <sender-info v-if="ele.type === 'orderAddress'"
                           :value.sync="form.fromContact[ele.prop]"
                           align="center"
                           :placeholder="`请输入${ele.label}`"
                           :type="ele.argName"
                           :max="ele.max"
                           :customer-id="form.customerId"
                           @input="selectFromAddress" />
            </el-form-item>
          </div>
          <div v-else-if="item.fromAddress && item.fromAddress.length > 0"
               :key="index">
            <el-form-item v-for="(ele, i) in item.fromAddress"
                          :key="`Address${i}`"
                          :label="ele.label"
                          :prop="`fromAddress.${[ele.prop]}`"
                          :rules=" [{ 
                            required: true,
                            message: `${ele.type === 'area' ? '请选择' : '请输入'}${ele.label}`,
                            trigger: 'change'
                          }]">
              <area-select v-if="ele.type === 'area'"
                           type="code"
                           :value.sync="form.fromAddress[ele.prop]"
                           align="center"
                           :area-values="[
                  form.fromAddress.provinceCode,
                  form.fromAddress.cityCode,
                  form.fromAddress.districtCode
                ]"
                           @confirm="selectFromArea" />
              <sender-info v-else
                           :value.sync="form.fromAddress[ele.prop]"
                           :placeholder="`请输入${ele.label}`"
                           align="center"
                           :type="ele.argName"
                           :max="ele.max"
                           :customer-id="form.customerId"
                           @input="selectFromAddress" />
            </el-form-item>
          </div>
          <div v-else-if="item.type === 'pactCode'"
               :key="index">
            <el-form-item :key="index"
                          :label="item.label"
                          :prop="item.prop"
                          :rules="[
                {
                  required: true,
                  message: `请输入合同编号，只可输入数字、字母和特殊符号(-_()&+/[])`,
                  validator: validatePactCode,
                  trigger: 'blur'
                },
                // {
                //   required: true,
                //   message: `合同编号与已存在的订单合同编号重复！`,
                //   validator: validateRepeatCode,
                //   trigger: 'blur'
                // }
              ]">
              <el-input v-model="form[item.prop]"
                        :placeholder="`请输入${item.label}`"
                        maxlength="30"
                        @blur="handleRepeatPactCode"></el-input>
            </el-form-item>
            <div class="repeat_tips">
              <div v-if="repeatFlag">
                <icon-svg class-name="iconClass mlr"
                          icon-name="tishi" />
                合同编号与已存在的订单合同编号重复！
              </div>
            </div>
          </div>
          <el-form-item v-else
                        :key="index"
                        :label="item.label"
                        :prop="item.prop"
                        :rules="[
              {
                required: true,
                message: `${
                  item.type === 'customer' || item.type === 'date'
                    ? '请选择'
                    : '请输入'
                }${item.label}`,
                trigger: 'change'
              }
            ]">
            <div v-if="item.type === 'customer'">
              <select-customer :value.sync="form.customerName"
                               @input="selectCustomer" />
              <span v-if="!form.customerId && form.customerName"
                    class="addCustomerTips">发货方名称为新增</span>
            </div>
            <el-date-picker v-else-if="item.type === 'date'"
                            v-model="form.fromTime"
                            align="left"
                            style="width: 100%"
                            type="datetime"
                            :placeholder="`请选择${item.label}`"
                            format="yyyy-MM-dd HH:mm"
                            :picker-options="fromTimePickerOptions"
                            :default-time="'00:00:00'"
                            popper-class="no-atTheMoment"
                            @change="changeTime(form.fromTime, 0)"></el-date-picker>
            <el-input v-else
                      v-model="form[item.prop]"
                      :placeholder="`请输入${item.label}`"></el-input>
          </el-form-item>
        </template>
      </el-col>
      <el-col :span="3"
              class="address-info-center"> &nbsp;</el-col>
      <el-col :span="8">
        <template v-for="(item, index) in receiveData">
          <div v-if="item.toContact && item.toContact.length > 0"
               :key="index">
            <el-form-item v-for="(ele, i) in item.toContact"
                          :key="i"
                          :label="ele.label"
                          :prop="`toContact.${[ele.prop]}`"
                          :rules="[
                {
                  required: true,
                  message: `请输入${ele.label}`,
                  trigger: 'blur'
                }
              ]">
              <consignee-info v-if="ele.type === 'orderAddress'"
                              :value.sync="form.toContact[ele.prop]"
                              :placeholder="`请输入${ele.label}`"
                              align="center"
                              :type="ele.argName"
                              :max="ele.max"
                              :customer-id="form.customerId"
                              @input="selectToAddress" />
            </el-form-item>
          </div>
          <div v-else-if="item.toAddress && item.toAddress.length > 0"
               :key="index">
            <el-form-item v-for="(ele, i) in item.toAddress"
                          :key="`Address${i}`"
                          :label="ele.label"
                          :prop="`toAddress.${[ele.prop]}`"
                          :rules=" [{ 
                            required: true,
                            message: `${ele.type === 'area' ? '请选择' : '请输入'}${ele.label}`,
                            trigger: 'change'
                          }]">
              <area-select v-if="ele.type === 'area'"
                           :value.sync="form.toAddress[ele.prop]"
                           type="code"
                           align="center"
                           :area-values="[
                  form.toAddress.provinceCode,
                  form.toAddress.cityCode,
                  form.toAddress.districtCode
                ]"
                           @confirm="selectToArea" />
              <consignee-info v-else-if="ele.type === 'orderAddress'"
                              :value.sync="form.toAddress[ele.prop]"
                              :placeholder="`请输入${ele.label}`"
                              align="center"
                              :type="ele.argName"
                              :max="ele.max"
                              :customer-id="form.customerId"
                              @input="selectToAddress" />
            </el-form-item>
          </div>
          <el-form-item v-else
                        :key="index"
                        :label="item.label"
                        :prop="item.prop"
                        :rules="[
              {
                required: true,
                message: `${
                  item.type === 'days' || item.type === 'date'
                    ? '请选择'
                    : '请输入'
                }${item.label}`,
                trigger: 'blur'
              }
            ]">
            <el-date-picker v-if="item.type === 'date'"
                            v-model="form.toTime"
                            align="left"
                            type="datetime"
                            style="width: 100%"
                            :placeholder="`请选择${item.label}`"
                            format="yyyy-MM-dd HH:mm"
                            :default-time="'23:59:59'"
                            popper-class="no-atTheMoment"
                            :picker-options="pickerOptions"
                            @change="changeTime(form.toTime, 1)"></el-date-picker>
            <el-select v-else-if="item.type === 'days'"
                       v-model="form.days"
                       style="width: 100%"
                       :placeholder="`请选择${item.label}`"
                       :disabled="!form.toTime && !form.fromTime"
                       @change="receivingDays">
              <!-- :disabled="form.fromTimeFlag" -->
              <el-option :value="0"
                         label="当天">当天</el-option>
              <el-option v-for="i in 30"
                         :key="i"
                         :value="i">{{ i }}天</el-option>
            </el-select>
            <consignee-info v-else-if="item.type === 'orderAddress'"
                            :value.sync="form[item.prop]"
                            :type="item.argName"
                            :max="item.max"
                            :placeholder="`请输入${item.label}`"
                            :customer-id="form.customerId"
                            @input="selectToAddress" />
            <el-input v-else
                      v-model="form[item.prop]"></el-input>
          </el-form-item>
        </template>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import baseMixin from "@components/mount/mixins/common";
import SelectCustomer from "./components/SelectCustomer.vue";
import AreaSelect from "@basic/area/AreaCodeSelect.vue";
import ConsigneeInfo from "@components/advance/orderAddress/ConsigneeInfo.vue";
import SenderInfo from "@components/advance/orderAddress/SenderInfo.vue";
import { order, shippingAddress } from "@/api/index.js";
import timeLinkage from "@/libs/timeLinkage";
import { returnCompareTime } from "@/libs/util.js";
import { mapState } from "vuex";
export default {
  name: "AddressInfo",
  components: {
    AreaSelect,
    ConsigneeInfo,
    SenderInfo,
    SelectCustomer
  },
  mixins: [baseMixin, timeLinkage],
  props: {
    formInfo: Object,
    emptyForm: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      shipData: [
        {
          label: "合同编号",
          prop: "contractNo",
          type: "pactCode"
        },
        {
          label: "发货方名称",
          prop: "customerName",
          type: "customer"
        },
        {
          fromContact: [
            {
              label: "发货联系人",
              prop: "contactName",
              type: "orderAddress",
              argName: "contactName",
              max: 20
            },
            {
              label: "联系电话",
              prop: "contactMobile",
              type: "orderAddress",
              argName: "contactMobile",
              max: 50
            }
          ]
        },
        {
          fromAddress: [
            {
              label: "发货省市区",
              prop: "districtCode",
              type: "area",
              argName: "contactName"
            },
            {
              label: "详细地址",
              prop: "address",
              argName: "address",
              max: 100
            }
          ]
        },
        {
          label: "发货时间",
          prop: "fromTime",
          type: "date"
        }
      ],
      receiveData: [
        {
          label: "收货方名称",
          prop: "consigneeName",
          type: "orderAddress",
          argName: "consigneeName",
          max: 80
        },
        {
          toContact: [
            {
              label: "收货联系人",
              prop: "contactName",
              type: "orderAddress",
              argName: "contactName",
              max: 20
            },
            {
              label: "联系电话",
              prop: "contactMobile",
              type: "orderAddress",
              argName: "contactMobile",
              max: 50
            }
          ]
        },
        {
          toAddress: [
            {
              label: "收货省市区",
              prop: "province",
              type: "area",
              argName: "contactName"
            },
            {
              label: "详细地址",
              prop: "address",
              type: "orderAddress",
              argName: "address",
              max: 100
            }
          ]
        },
        {
          label: "收货时效天数",
          prop: "days",
          type: "days"
        },
        {
          label: "收货时间",
          prop: "toTime",
          type: "date"
        }
      ],
      fromTimePickerOptions: {
        // 时间选择限制 发货时间
        disabledDate: (time) => {
          if (this.systemBillObj.billDateFlag) {
            if (this.form.toTime) {
              return (
                time.getTime() <=
                new Date(
                  new Date(this.systemBillObj.sameMonthDay).setDate(
                    new Date(this.systemBillObj.sameMonthDay).getDate() - 1
                  )
                ).getTime() || time.getTime() > new Date(this.form.toTime).getTime()
              );
            } else {
              return (
                time.getTime() <=
                new Date(
                  new Date(this.systemBillObj.sameMonthDay).setDate(
                    new Date(this.systemBillObj.sameMonthDay).getDate() - 1
                  )
                ).getTime()
              );
            }
          } else if (this.form.toTime) {
            return (
              time.getTime() <=
              new Date(
                new Date(this.systemBillObj.lastMonthDay).setDate(
                  new Date(this.systemBillObj.lastMonthDay).getDate() - 1
                )
              ).getTime() || time.getTime() > new Date(this.form.toTime).getTime()
            )
          } else {
            return (
              time.getTime() <=
              new Date(
                new Date(this.systemBillObj.lastMonthDay).setDate(
                  new Date(this.systemBillObj.lastMonthDay).getDate() - 1
                )
              ).getTime()
            )
          }
        }
      },
      pickerOptions: {
        // 时间选择限制 收货时间
        disabledDate: (time) => {
          if (this.systemBillObj.billDateFlag) {
            let toTimeInit = returnCompareTime(
              new Date(this.$moment(this.form.fromTime).format("YYYY-MM-DD HH:mm:ss")),
              new Date(this.$moment(this.systemBillObj.sameMonthDay).format("YYYY-MM-DD 23:59:59"))
            ) ? this.form.fromTime : this.systemBillObj.sameMonthDay;
            return (
              time.getTime() <=
              new Date(
                new Date(toTimeInit).setDate(
                  new Date(toTimeInit).getDate() - 1
                )
              ).getTime()
            );
          } else if (this.form.fromTime) {
            return (
              time.getTime() <=
              new Date(
                new Date(this.form.fromTime).setDate(
                  new Date(this.form.fromTime).getDate() - 1
                )
              ).getTime()
            );
          } else {
            return (
              time.getTime() <=
              new Date(
                new Date(this.systemBillObj.lastMonthDay).setDate(
                  new Date(this.systemBillObj.lastMonthDay).getDate() - 1
                )
              ).getTime()
            );
          }
        },
        selectableRange: `00:00:00 - 23:59:59`
      },
      tableData: [{}],
      form: {},
      showGoods: false, // 物品组件
      isSender: false,
      isDeploy: false,
      isOrders: false,
      repeatFlag: false, // 合同编号是否重复
    };
  },
  computed: {
    ...mapState({
      systemBillDateInfo: (state) => state.login.systemBillDateInfo || null
    }),
    systemBillObj () {
      console.log("==========systemBillObj", this.systemBillDateInfo)
      return {
        billDateFlag: null,   //是否已过关账期
        lastMonthDay: null,   // 关账期前一月的第一天
        sameMonthDay: null,   // 关账期当月的第一天
        ...this.systemBillDateInfo
      }
    }
  },
  watch: {
    emptyForm: {
      deep: true,
      handler (val) {
        this.form = val;
      }
    },
    formInfo: {
      deep: true,
      immediate: true,
      handler (val) {
        this.form = val;
        this.handlerChangeTime(this.form);
      }
    }
  },
  created () {
    // this.systemBillObj = { ...this.systemBillDateInfo };
    this.form = this.formInfo;
    this.handlerChangeTime(this.form);
  },
  methods: {
    async getConfig () {
      if (this.form.customerId) {
        let { data } = await order.getCreateConfig(this.form.customerId);
        if (data) {
          data.goodsCategory = data.goodsCategory === 0 ? null : data.goodsCategory;
          data.packageMode = data.packageMode === 0 ? null : data.packageMode;
          data.chargeMode = data.chargeMode || 2;
          data.priceUnit = data.priceUnit || 3;
          data.goodsType = data.goodsType + '';
          Object.assign(this.form, data);
        } else {
          const obj = {
            transportMode: 1,
            chargeMode: 2,
            priceUnit: 3,
            pick: false, deliver: false, onLoad: false, offLoad: false, insure: null, packageMode: null, goodsType: null, goodsCategory: null
          };
          Object.assign(this.form, obj);
        }
        this.form.vehicleMode.vehicleCount = 1;
      }
    },
    // 客户默认地址
    async getCustInfo (customerId) {
      if (customerId) {
        let {
          data: { records }
        } = await shippingAddress.search({ customerId, isDefault: true });
        let obj = records && records.length > 0 ? records[0] : null;

        if (obj) {
          this.form.fromAddress = Object.assign(this.form.fromAddress, obj);
          this.form.fromContact = Object.assign(this.form.fromContact, obj);
        } else {
          this.form.fromAddress = {
            address: null,
            city: null,
            cityCode: null,
            district: null,
            districtCode: null,
            province: null,
            provinceCode: null
          };
          this.form.fromContact = { contactName: null, contactMobile: null };
        }
      }
    },
    // 合同编号输入校验
    validatePactCode (rule, value, callback) {
      if (value) {
        if (
          value &&
          value.match(/^[a-zA-Z0-9\-\_\(\)\&\+\/\[\]]{0,30}$/) == null
        ) {
          callback(
            new Error("请输入合同编号，只可输入数字、字母和特殊符号(-_()&+/[])")
          );
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入合同编号"));
      }
    },
    // async validateRepeatCode (rule, value, callback) {
    //   if (value) {
    //     const isPactCode = await this.handleRepeatPactCode()
    //     if (!isPactCode && isPactCode !== undefined) {
    //       callback(new Error('合同编号与已存在的订单合同编号重复！'));
    //     } else {
    //       callback();
    //     }
    //   } else {
    //     callback(new Error("请输入合同编号"));
    //   }
    // },
    //合同重复校验
    async handleRepeatPactCode () {
      if (!this.form.contractNo) {
        return;
      }
      let { data } = await order.validateRepeatContractNo({
        contractNo: encodeURIComponent(this.form.contractNo)
      });
      this.repeatFlag = !data;
    },
    // 选择客户
    selectCustomer (val) {
      if (val.customerId != this.form.customerId) {
        this.form.consigneeName = null;
        this.form.toContact = { contactName: "", contactMobile: "" };
        for (let key in this.form.toAddress) {
          this.form.toAddress[key] = "";
        }
      }
      this.form.customerName = val.name ? val.name : val;
      this.form.customerId = val.customerId ? val.customerId : null;
      this.form.goodsList = [];
      if (this.form.customerId) {
        this.getConfig(this.form.customerId);
        this.getCustInfo(this.form.customerId);
      } else {
        for (let key in this.form.fromContact) {
          this.form.fromContact[key] = "";
        }
        for (let key in this.form.fromAddress) {
          this.form.fromAddress[key] = "";
        }
        for (let key in this.form.toContact) {
          this.form.toContact[key] = "";
        }
        for (let key in this.form.toAddress) {
          this.form.toAddress[key] = "";
        }
        this.form = {
          chargeMode: 2,
          deliver: false,
          offLoad: false,
          onLoad: false,
          pick: false,
          vehicleMode: {
            vehicleCount: 1
          },
          priceUnit: 3,
          shipMode: 0,
          transportMode: 1
        };
      }
      this.vaild(); //重新校验表单
    },
    // 选择发货省市区
    selectFromArea (val) {
      this.form.fromAddress = Object.assign(this.form.fromAddress, val);
      this.vaild(); //重新校验表单
    },
    // 选择收货省市区
    selectToArea (val) {
      this.form.toAddress = Object.assign(this.form.toAddress, val);
      this.vaild(); //重新校验表单
    },
    // 选择发货地址
    selectFromAddress (val) {
      let { fromAddress, fromContact } = this.form;
      let { contactName, contactMobile, ...params } = val;
      fromContact.contactName = contactName;
      fromContact.contactMobile = contactMobile;
      fromAddress = Object.assign(fromAddress, params);
      this.vaild(); //重新校验表单
      return this.form;
    },
    // 选择收货地址
    selectToAddress (val) {
      let { toAddress, toContact } = this.form;
      let { contactName, contactMobile, consigneeId, consigneeName, ...params } = val;
      toContact.contactName = contactName;
      toContact.contactMobile = contactMobile;
      toAddress = Object.assign(toAddress, params);
      this.form = Object.assign(this.form, { consigneeName: consigneeName, consigneeId: consigneeId });
      this.vaild(); //重新校验表单
      return this.form;
    },
    vaild () {
      this.$refs.ruleForm.validate((valid) => {
        console.log("==========validate", valid)
      });
      // this.$refs.ruleForm.clearValidate()
    },
    resetInfo () {
      this.$refs.ruleForm.resetFields();
      this.form.contractNo = "";
      this.form.customerName = "";
      this.form.customerId = null;
      this.form.fromTime = "";
      this.form.consigneeId = null;
      this.form.consigneeName = "";
      this.form.days = null;
      this.form.toTime = "";
      // this.form.fromTimeFlag = false;
      this.pickerOptions.selectableRange = `00:00:00 - 23:59:59`;
      for (let key in this.form.fromContact) {
        this.form.fromContact[key] = "";
      }
      for (let key in this.form.fromAddress) {
        this.form.fromAddress[key] = "";
      }
      for (let key in this.form.toContact) {
        this.form.toContact[key] = "";
      }
      for (let key in this.form.toAddress) {
        this.form.toAddress[key] = "";
      }
    }
  }
};
</script>
<style lang="scss" scope>
.create_form {
  // overflow: hidden;
  padding-top: 90px;
  padding-bottom: 20px;
  // height: calc(100vh - 350px);
  .el-input__inner {
    height: 36px !important;
    line-height: 36px !important;
    font-size: 14px;
  }
}
.addCustomerTips {
  color: var(--prev-color-primary);
  font-size: 12px;
}
.no-atTheMoment
  .el-picker-panel__footer
  .el-button--text.el-picker-panel__link-btn {
  display: none !important;
}
.address-info-center {
  // position: relative;
  &:after {
    content: "";
    width: 1px;
    height: 425px;
    background: var(--prev-bg-color);
    position: absolute;
    right: 50%;
    top: 0;
  }
}
.repeat_tips {
  color: var(--prev-border-color-yellow);
  position: absolute;
  top: 38px;
  left: 300px;
  font-size: 12px;
}
</style>
